package fr.upstlse.glre.client.utilitaires;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.ServiceDefTarget;

import fr.upstlse.glre.client.controler.ControlerService;
import fr.upstlse.glre.client.controler.ControlerServiceAsync;
import fr.upstlse.glre.client.controler.UserControlerService;
import fr.upstlse.glre.client.controler.UserControlerServiceAsync;

public class ControlerUtil {

	private static ControlerServiceAsync controlerServiceAsyncInstance;

	private static UserControlerServiceAsync userControlerServiceAsyncInstance;

	public static ControlerServiceAsync getControlerServiceAsyncInstance() {
		if (controlerServiceAsyncInstance == null) {
			controlerServiceAsyncInstance = (ControlerServiceAsync) GWT
					.create(ControlerService.class);
			ServiceDefTarget lEndPoint = (ServiceDefTarget) controlerServiceAsyncInstance;
			String lServiceUrl = GWT.getModuleBaseURL() + "controlerService";
			lServiceUrl = getRealUrl(lServiceUrl);
			lEndPoint.setServiceEntryPoint(lServiceUrl);
			//MessageBox.alert("DEBUG", lServiceUrl, null);
		}
		return controlerServiceAsyncInstance;
	}

	public static UserControlerServiceAsync getUserControlerServiceAsyncInstance() {
		if (userControlerServiceAsyncInstance == null) {
			userControlerServiceAsyncInstance = (UserControlerServiceAsync) GWT
					.create(UserControlerService.class);
			ServiceDefTarget lEndPoint = (ServiceDefTarget) userControlerServiceAsyncInstance;
			String lServiceUrl = GWT.getModuleBaseURL() + "userControlerService";
			lServiceUrl = getRealUrl(lServiceUrl);
			lEndPoint.setServiceEntryPoint(lServiceUrl);
			//MessageBox.alert("DEBUG", lServiceUrl, null);
		}

		return userControlerServiceAsyncInstance;
	}
	
	private static String getRealUrl(String pBadUrl) {
		String lRealUrl = pBadUrl;
		String[] lSplitedUrl = pBadUrl.split("/");
		if(lSplitedUrl.length == 6){
			lRealUrl = lSplitedUrl[0] + "//" + lSplitedUrl[2] + "/" + lSplitedUrl[3] + "/" + lSplitedUrl[5];
		}
		
		return lRealUrl;
	}

}
